class Solution {
public:
    string decodeString(string s) {
        string ret;
        stack<char> mystack;

        for (auto ch : s)
        {
            if (ch == ']')
            {
                //获取【】内的字符
                string ch_str;
                while (mystack.top() != '[')
                {
                    ch_str += mystack.top();
                    mystack.pop();
                }
                mystack.pop();

                //获取被重复的次数
                string count_str;
                while (!mystack.empty() && isdigit(mystack.top()))
                {
                    count_str += mystack.top();
                    mystack.pop();
                }
                reverse(count_str.begin(), count_str.end());

                //将解码后的字符重新放入栈中
                int count = stoi(count_str);
                while (count--)
                {
                    for (int i = ch_str.size() - 1; i >= 0; i--)
                        mystack.push(ch_str[i]);
                }
            }
            else
                mystack.push(ch);
        }

        while (!mystack.empty())
        {
            ret += mystack.top();
            mystack.pop();
        }

        reverse(ret.begin(), ret.end());
        return ret;
    }
};